package org.example;

import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.EnvironmentSettings;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

public class PaimonTruncatePartition {
    public static void main(String[] args) {
        // 创建Flink流执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        EnvironmentSettings settings = EnvironmentSettings.newInstance().build();

        // INSERT OVERWRITE必须开启batch模式
        env.setRuntimeMode(RuntimeExecutionMode.BATCH);

        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env, settings);

        // 创建Paimon catalog
        tableEnv.executeSql("CREATE CATALOG paimon WITH (" +
                "    'type' = 'paimon'," +
                "    'warehouse' = 'file:///tmp/paimon'" +
                ");");

        tableEnv.executeSql("CREATE TABLE IF NOT EXISTS `paimon`.`default`.`user_behavior_copy` (\n" +
                "    user_id STRING,\n" +
                "    item_id STRING,\n" +
                "    behavior BIGINT,\n" +
                "    dt STRING,\n" +
                "    eventtime TIMESTAMP_LTZ(3),\n" +
                "    WATERMARK FOR eventtime AS eventtime - INTERVAL '5' SECOND,\n" +
                "    PRIMARY KEY (dt, user_id) NOT ENFORCED\n" +
                ") PARTITIONED BY (dt)\n" +
                ";");

        // 不加/*+ OPTIONS('dynamic-partition-overwrite'='false') */
        tableEnv.executeSql(
                "INSERT OVERWRITE `paimon`.`default`.user_behavior_copy  partition(dt='2025-01-11') (user_id, item_id, behavior, eventtime)\n" +
                        "SELECT user_id\n" +
                        ", item_id\n" +
                        ", behavior\n" +
                        ", cast(eventtime as TIMESTAMP(3))\n" +
                        "FROM `paimon`.`default`.user_behavior_copy WHERE false;"
        );
    }
}
